
#include "TwSkyBox.h"
#include <d3d9types.h>
#include "../TwTexture.h "
#include "../camera/TwCamera.h"

void TwSkyBox::Init()
{
	LPD3DXBUFFER bufShipMaterial;

	if( FAILED( D3DXLoadMeshFromX(
		(LPCSTR)"E:\\outcode\\media\\models\\unit_dome.x", 
		D3DXMESH_MANAGED, 
		g_Render->GetDevice(), 
		NULL, 
		NULL, 
		NULL,
		&m_numMaterials, 
		&m_pMesh ) ) )
		return;

	TwTexture* pkTexutre = g_Render->GetTextureMgr()->CreateTexture("E:\\outcode\\media\\textures\\sky_box0.dds");
	m_pSkyTextures =  (LPDIRECT3DTEXTURE9)pkTexutre->GetData();

	pkTexutre = g_Render->GetTextureMgr()->CreateTexture("E:\\outcode\\media\\textures\\clouds.dds");
	m_pSkyTextures1 =  (LPDIRECT3DTEXTURE9)pkTexutre->GetData();

	m_uvScaleOffset.x = 0.0f;
	m_uvScaleOffset.y = 0.0f;
	m_uvScaleOffset.z = 0.0f;
	m_uvScaleOffset.w = 0.0f;

	LPD3DXBUFFER errorlog;    // for storing errors

	D3DXCreateEffectFromFile(g_Render->GetDevice(), (LPCSTR)"E:\\outcode\\media\\shaders\\simple_skydome.fx", 0, 0, 0, 0, &m_pkeffect, &errorlog);

	if(m_pkeffect == NULL)
	{
		::MessageBox(NULL,(LPCSTR)errorlog->GetBufferPointer(),NULL,0);
	}
	m_pkeffect->SetTechnique("BasicCubeMap");
	m_pkeffect->SetTexture("tex0",m_pSkyTextures);
	m_pkeffect->SetTexture("tex1",m_pSkyTextures1);
	
}

void TwSkyBox::Update()
{
	m_uvScaleOffset.x += 0.00025f;
	m_uvScaleOffset.y += 0.00035f;
	m_uvScaleOffset.z += 0.0004f;
	m_uvScaleOffset.w += 0.0005f;
	m_pkeffect->SetFloatArray("uv_data", &m_uvScaleOffset.x, 4); 
}

void TwSkyBox::Render()
{


	static float index = -1.57f;  
	D3DXMATRIX matRotateY;
	D3DXMatrixRotationX(&matRotateY, index);
	g_Render->GetDevice()->SetTransform(D3DTS_WORLD, &(matRotateY));
	D3DXMATRIXA16 mWorld, matView, mProj;
	g_Render->GetDevice()->GetTransform(D3DTS_WORLD, &mWorld);
	g_Render->GetDevice()->GetTransform(D3DTS_VIEW, &matView);
	g_Render->GetDevice()->GetTransform(D3DTS_PROJECTION, &mProj);

	D3DXMATRIXA16 matworldviewProj = mWorld*matView*mProj;
	D3DXMATRIXA16 matworldview     = mWorld*matView;

	m_pkeffect->SetMatrix("mWorldViewProj", &matworldviewProj);

	g_Render->GetDevice()->SetRenderState(D3DRS_ZENABLE, FALSE);
	g_Render->GetDevice()->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW );
	g_Render->GetDevice()->SetRenderState( D3DRS_AMBIENT, 0xffffffff );
	g_Render->GetDevice()->SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE );

	D3DXMatrixRotationY(&matRotateY, -index);
	g_Render->GetDevice()->SetTransform(D3DTS_WORLD, &(matRotateY));

	m_pkeffect->Begin(NULL, NULL);   
	m_pkeffect->BeginPass(0);   
	 
	m_pMesh->DrawSubset(0);   
	m_pkeffect->EndPass();    
	m_pkeffect->End();    


}

void TwSkyBox::Clear()
{
	SAFE_RELEASE(m_pMesh);
}